<?php

namespace app\adminapi\http\middleware;

use app\common\model\auth\Admininfo;
use app\common\service\JsonService;
use app\Request;

class MerchantMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        $timestamp = $request->header('timestamp');
        $headerSign = $request->header('sign');
        $nonce = $request->header('nonce');
        if (!$headerSign || !$nonce || !$timestamp || abs(round($timestamp / 1000) - time()) > 60) {
            return JsonService::fail('无效访问', [], 0, 1);
        }
        $params = $request->param();
        ksort($params);
        $sign = hash_hmac("sha256", http_build_query($params) . '&nonce=' . $nonce . '&timestamp=' . $timestamp, "@1234567890");
        if ($headerSign !== $sign) {
            return JsonService::fail('无效访问', [
                'sign' => http_build_query($params),
            ], 0, 1);
        }

        // 判断当前账号是否是商户


        $adminInfo = Admininfo::findOrFail($request->adminId);
        if (!$adminInfo->merchant_id) {
            return JsonService::fail('无效访问', [], 0, 1);
        }
        $request->merhchant_id = $adminInfo->merchant_id;

        return $next($request);
    }
}